<?php

class errorHandler {
	private $mode;
	private $log;
	private $webRoot;
	private $appMode;
	private $error = array();

	function __construct($args = array()) {
		$this->mode = $args['mode'];
		$this->webRoot = $args['webRoot'];
		$this->appMode = $args['appMode'];
		$this->log = new log(array('fn'=>$args['logFile']));
	}

	function trigger($name, $details = array()) {
		if(file_exists('app/errors/definitions/'.$name.'.php')) {
			require('app/errors/definitions/'.$name.'.php');
		} else if(file_exists('core/errors/definitions/'.$name.'.php')) {
			require('core/errors/definitions/'.$name.'.php');
		} else {
			die('The definition of the error '.$name. ' could not be found.');
		}

		$this->log->write($title.':'.
			NL.$description.
			NL.var_export($details, true).
			NL.$name.
			NL
		);

		sins($fatal, true);
		sins($view, 'default');
		sins($template, 'default');
		sins($http, '500');

		if(headers_sent() || $this->mode==AETHER_CLI) {
			echo NL.'Error: '.$description.' '.NL;
			if($this->appMode==AETHER_DEVELOPMENT) {
				echo 'Details: '.NL.var_export($details, true).' '.NL;
			}
			die('Error name: '.$name);
		} else {
			if($http=='404') {
				header('HTTP/1.1 404 Not Found');
			} else if($http=='403') {
				header('HTTP/1.1 403 Forbidden');
			} else {
				header('HTTP/1.1 500 Internal Server Error');
			}
			if(isset($redirect)&&$this->mode==AETHER_WEB) {
				$_GET['details'] = $details;
				$this->h->core->redeclare($redirect);
				exit;
			} else {
				$this->error['name'] = $name;
				$this->error['title'] = $title;
				$this->error['description'] = $description;
				$this->error['details'] = $details;
				$this->error['view'] = $view;
				if(file_exists('app/errors/templates/'.$template.'.php')) {
					require('app/errors/templates/'.$template.'.php');
				} else if(file_exists('core/errors/templates/'.$template.'.php')) {
					require('core/errors/templates/'.$template.'.php');
				} else {
					die('Error template not found.');
				}
			}
		}
		if($fatal) {
			exit;
		}
	}

	private function yield() {
		if(file_exists('app/errors/views/'.$this->error['view'].'.php')) {
			require('app/errors/views/'.$this->error['view'].'.php');
		} else if(file_exists('core/errors/views/'.$this->error['view'].'.php')) {
			require('core/errors/views/'.$this->error['view'].'.php');
		} else {
			die('View '.$this->error['view'].' does not exist.');
		}
	}
}

//EOF
